package com.crpc.network.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class Client {

    public static void main(String[] args) throws Exception {

        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(new NioEventLoopGroup());
        bootstrap.channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("encode",new TestChannelHandler());
                pipeline.addLast("decode",new TestChannelHandler());
            }
        });

        ChannelFuture channelFuture = bootstrap.connect("localhost",10000);

        channelFuture.await();

        Channel channel = channelFuture.channel();
        String msg = "hello";
        channel.writeAndFlush(msg);

        LockSupport.parkNanos(TimeUnit.MINUTES.toNanos(30));
    }

    private static class TestChannelHandler extends ChannelInboundHandlerAdapter {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("Client-收到消息类型" + msg.getClass().getName());
            System.out.println("Client-收到消息: " + msg);
        }
    }
}
